<?php
session_start();
require_once 'database.php';
header('Content-Type: application/json');

function default_response($data = [], $status = 'success', $code = 200)
{
    http_response_code($code);
    echo json_encode(array_merge(['status' => $status], $data));
}

// 新增的查询函数
function getTrainingCostData($school, $start_time, $end_time)
{
    global $pdo;

    $sql = "SELECT t.*, tt.title, tt.start_time, tt.end_time, tt.location, tt.type
         FROM trainings_teachers t
         LEFT JOIN trainings tt ON tt.id = t.training_id
         WHERE " . ($school === '所有单位' ? '' : 't.teacher_school = ? AND ') . "tt.start_time BETWEEN ? AND ?
         ORDER BY t.teacher_id";

    // 查询trainings_teachers表和trainings表
    $stmt = $pdo->prepare($sql);

    if ($school == '所有单位') {
        $stmt->bindParam(1, $start_time, PDO::PARAM_STR);
        $stmt->bindParam(2, $end_time, PDO::PARAM_STR);
    } else {
        $stmt->bindParam(1, $school, PDO::PARAM_STR);
        $stmt->bindParam(2, $start_time, PDO::PARAM_STR);
        $stmt->bindParam(3, $end_time, PDO::PARAM_STR);
    }
    if ($stmt->execute()) {
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $data;
    }
    return false;
}

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // 新增的数据查询逻辑
        if (isset($_POST['school']) && isset($_POST['start_time']) && isset($_POST['end_time'])) {
            $data = getTrainingCostData($_POST['school'], $_POST['start_time'], $_POST['end_time']);
            if ($data !== false) {
                default_response(["data" => $data]);
            } else {
                default_response(["message" => "没有找到相关数据"], "error", 404);
            }
        } else {
            default_response(["message" => "缺少必要的参数" . $_POST], "error", 400);
        }
    } else {
        default_response(["message" => "无效的请求方法"], "error", 405);
    }
} catch (Exception $e) {
    default_response(["message" => $e->getMessage()], "error", 500);
}